package main

import (
	"booking-service/internal/handlers"
	"booking-service/internal/services"
	"booking-service/internal/storage/memory"
	"github.com/joho/godotenv"
	log "github.com/sirupsen/logrus"
	"net/http"
	"os"
	"time"
)

func main() {
	// Загрузка переменных окружения из .env файла
	err := godotenv.Load()
	if err != nil {
		log.Fatalf("Error loading .env file")
	}

	port := os.Getenv("SERVER_PORT")
	if port == "" {
		log.Fatalf("SERVER_PORT is not set in the environment variables")
	}

	logLevel := os.Getenv("LOG_LEVEL")
	if logLevel == "" {
		logLevel = "info" // значение по умолчанию
	}
	level, err := log.ParseLevel(logLevel)
	if err != nil {
		log.Fatalf("Invalid log level: %s", logLevel)
	}
	log.SetLevel(level)
	log.SetFormatter(&log.JSONFormatter{})

	orderStorage := &memory.InMemoryOrderStorage{}
	roomStorage := memory.NewInMemoryRoomAvailabilityStorage()

	// Инициализация доступности номеров
	if err := initializeRoomAvailability(roomStorage); err != nil {
		log.Fatalf("Failed to initialize room availability: %v", err)
	}

	bookingService := services.NewBookingService(orderStorage, roomStorage)
	bookingHandler := handlers.NewBookingHandler(bookingService)

	mux := http.NewServeMux()
	mux.HandleFunc("/orders", bookingHandler.CreateOrder)

	log.Infof("Server listening on localhost:%s", port)
	if err := http.ListenAndServe(":"+port, mux); err != nil {
		log.Fatalf("Server failed: %v", err)
	}
}

func initializeRoomAvailability(storage *memory.InMemoryRoomAvailabilityStorage) error {
	var err error

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-02: %v", err)
		return err
	}

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 3, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-03: %v", err)
		return err
	}

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 4, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-04: %v", err)
		return err
	}

	return nil
}
